﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Traceability
{
    public class TraceabilityEaditCommandHandler : IRequestHandler<TraceabilityEaditCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Traceability> tranceRepository;
        private readonly IMapper mapper;

        public TraceabilityEaditCommandHandler(IBaseRepository<T_Traceability> tranceRepository, IMapper mapper)
        {
            this.tranceRepository = tranceRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(TraceabilityEaditCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;

            if (request.IsUpdateOrDel == true)
            {
                var models = tranceRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch && x.ID != request.ID);
                if (models != null)
                {
                    result.Code = APIEnum.fail;
                    result.Message = "生产批次已存在";
                    return await Task.FromResult(result);
                }
                result.Message = "修改成功";
                var model = mapper.Map<T_Traceability>(request);
                result.Data = await tranceRepository.Update(model);
                return await Task.FromResult(result);
            }
            else
            {
                result.Message = "删除成功";
                var model = mapper.Map<T_Traceability>(request);
                model.IsDelete = true;
                result.Data = await tranceRepository.Update(model);
                return await Task.FromResult(result);
            }
        }
    }
}
